package com.todo.dao;

import com.todo.model.User;
import com.todo.util.DatabaseUtil;

import java.sql.*;

public class UserDAO {
    
    public void register(User user) throws SQLException {
        if (user == null || user.getUsername() == null || user.getPassword() == null || user.getEmail() == null) {
            throw new SQLException("用户信息不完整");
        }

        String sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            System.out.println("数据库连接成功，使用的数据库：" + conn.getCatalog());
            
            // 检查用户名和邮箱是否已存在
            if (isUsernameExists(user.getUsername())) {
                throw new SQLException("用户名已存在");
            }
            if (isEmailExists(user.getEmail())) {
                throw new SQLException("邮箱已被注册");
            }
            
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, user.getUsername().trim());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getEmail().trim().toLowerCase());
            
            System.out.println("执行SQL: " + sql);
            System.out.println("参数: username=" + user.getUsername() + ", email=" + user.getEmail());
            
            int rowsAffected = pstmt.executeUpdate();
            System.out.println("SQL执行结果 - 影响的行数: " + rowsAffected);
            
            // 验证数据是否真的插入
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE username='" + user.getUsername() + "'")) {
                if (rs.next()) {
                    System.out.println("验证：数据已成功插入，ID=" + rs.getLong("id"));
                } else {
                    System.out.println("警告：数据似乎没有正确插入");
                }
            }
            
            // 获取生成的主键
            try (ResultSet rs = pstmt.getGeneratedKeys()) {
                if (rs.next()) {
                    user.setId(rs.getLong(1));
                }
            }
            
            conn.commit();
            System.out.println("事务已提交");
        } catch (SQLException e) {
            System.out.println("错误详情：" + e.getMessage());
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                    System.out.println("事务已回滚");
                } catch (SQLException ex) {
                    System.out.println("回滚失败: " + ex.getMessage());
                }
            }
            throw e;
        } finally {
            if (pstmt != null) try { pstmt.close(); } catch (SQLException e) { }
            if (conn != null) try { conn.close(); } catch (SQLException e) { }
        }
    }
    
    public User login(String username, String password) throws SQLException {
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, username);
            pstmt.setString(2, password); // 实际应用中应该验证加密后的密码
            
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    User user = new User();
                    user.setId(rs.getLong("id"));
                    user.setUsername(rs.getString("username"));
                    user.setEmail(rs.getString("email"));
                    return user;
                }
            }
        }
        return null;
    }
    
    public boolean isUsernameExists(String username) throws SQLException {
        String sql = "SELECT COUNT(*) FROM users WHERE username = ?";
        
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, username);
            
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1) > 0;
                }
            }
        }
        return false;
    }
    
    public boolean isEmailExists(String email) throws SQLException {
        String sql = "SELECT COUNT(*) FROM users WHERE email = ?";
        
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, email);
            
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1) > 0;
                }
            }
        }
        return false;
    }
} 